<?php
            
use app\model\Worker; 


/**
 * Author: cbw
 * Desc: 商家产品多次核销
 * Time: 2022/7/18 10:08
 * Email: 17854288794@163.com
 */
require_once PATH_MODULE .'define.php';
class SjMulitVerifyModel extends PluginModel{

    public static function getSjProductList($themeid,$search='',$status=0,$sj_id=0,$page_start=0,$page_size=10,$get_count = false)
    {
        $condition = "";
        if ($search) {
            $condition .= " and a.name LIKE '%".$search."%' or b.name like '%".$search."%' ";
        }
        if ($status>-1){
            $condition .= " and a.status=$status";
        }

        if ($sj_id ) {
            $condition .= " and a.shangjiaid='".$sj_id."'";
        }
        $condition .= " order by a.status desc, a.show_sort asc ";
        if ($page_size){
            $condition .= "  limit ".$page_start.",".$page_size;
        }
        if ($get_count){
            $sql = " SELECT count(*) as cnt FROM ".tablename(sj_mulit_products)." as a".
                " LEFT JOIN ".tablename(t_shangjia)." AS b ON a.shangjiaid=b.id ".
                " WHERE themeid=$themeid".$condition;
            return db_find($sql)['cnt'];
        }else{
            $sql = " SELECT a.*,b.name as shangjia_name FROM ".tablename(sj_mulit_products)." as a".
                " LEFT JOIN ".tablename(t_shangjia)." AS b ON a.shangjiaid=b.id ".
                " WHERE themeid=$themeid".$condition;
            return db_select($sql);
        }

    }

    /**
     * Desc:获取多产品记录 通过商家id\搜索、状态
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/23 16:12
     * @param $themeid
     * @param string $search
     * @param int $status
     * @param int $sj_id
     * @param int $p_id
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getSjProductFlagList($themeid,$search='',$status=-1,$sj_id=0,$p_id=0,$page_start=0,$page_size=10)
    {
        $condition = "";
        if ($search) {
            $condition .= " and b.name LIKE '%".$search."%'  ";
        }
        if ($status>-1){
            $condition .= " and a.status=$status";
        }
        if ($sj_id ) {
            $condition .= " and a.shangjiaid='".$sj_id."'";
        }
        if ($p_id){
            $condition .= " and a.product_id='".$p_id."'";
        }
        $condition .= " order by a.status desc ";
        if ($page_size){
            $condition .= "  limit ".$page_start.",".$page_size;
        }
        $sql = " select a.*,b.name,c.nickname,c.username,c.avatar,c.mobile from ".tablename(sj_mulit_products_user_flag)." as a".
                " left join ".tablename(sj_mulit_products)." as b on a.product_id=b.id ".
                " left join ".tablename(t_fans)." as c on a.uid=c.uid and c.themeid=$themeid".
                " where a.themeid=$themeid ".$condition;
        return db_select($sql);
    }

    /**
     * Desc:获取用户多产品信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/8/8 18:12
     * @param $themeid
     * @param string $search
     * @param int $sj_id
     * @param int $p_id
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getUserRecordSjProductList($themeid,$search='',$sj_id=0,$p_id=0,$page_start=0,$page_size=10,$get_total = false,$status=0,$order_id=0)
    {
        $condition = "";
        if ($search) {
            $condition .= " and b.name LIKE '%".$search."%' "." or c.username LIKE '%".$search."%' "." or c.nickname LIKE '%".$search."%' " ." or c.mobile LIKE '%".$search."%' ";
        }
        if ($sj_id ) {
            $condition .= " and a.shangjiaid='".$sj_id."'";
        }
        if ($p_id){
            $condition .= " and a.product_id='".$p_id."'";
        }
        $condition .= " and a.status=2 ";
        if ($order_id){
            $condition .= " and a.order_id='".$order_id."'";
        }
        $condition .= " and (d.status=1 or d.status=3) order by a.status desc ";
        if ($page_size){
            $condition .= "  limit ".$page_start.",".$page_size;
        }
        if ($get_total){
            $sql = " select count(*) as cnt from ".tablename(sj_mulit_products_user_flag)." as a".
                " left join ".tablename(sj_mulit_products)." as b on a.product_id=b.id ".
                " left join ".tablename(t_fans)." as c on a.uid=c.uid and c.themeid=$themeid".
                " left join ".tablename(t_record)." as d on a.order_id=d.id and d.themeid=$themeid".
                " where a.themeid=$themeid and b.status=1 ".$condition;
            $has_total =  db_find($sql)['cnt'];
            $order_total = (int)SjMulitVerifyModel::getOrderTotalByWhere($themeid);
            $product_total = (int)self::getSjProductStatusTotal($themeid,1,$sj_id);
            if ($status==1){
                //未核销
                if (!$order_id){
                    //指定人
                    $all_total  = $order_total*$product_total;
                }else{
                    //未指定人
                    $all_total  = $product_total;
                }
                return $all_total-$has_total;
            }elseif ($status==2){
                //已核销
                return  $has_total;
            }else{
                //全部
                return $order_total*$product_total;
            }
        }else{


            $condition = "";
            if ($status==1){
                $condition .= " and c.id is null ";
            }elseif ($status==2){
                $condition .= " and c.id is not null ";
            }
            if ($search) {
                $condition .= " and b.name LIKE '%".$search."%' "." or a.username LIKE '%".$search."%' "." or a.nickname LIKE '%".$search."%' " ." or a.mobile LIKE '%".$search."%' ";
            }
            if ($p_id){
                $condition .= " and b.id='".$p_id."'";
            }
            if ($sj_id ) {
                $condition .= " and b.shangjiaid='".$sj_id."'";
            }
            if ($order_id){
                $condition .= " and a.id='".$order_id."'";
            }
            $condition .= " and (a.status=1 or a.status=3) order by a.addtime desc ";
            if ($page_size){
                $condition .= "  limit ".$page_start.",".$page_size;
            }

            $sql = " select a.nickname,a.username,a.mobile,a.avatar,b.name,a.id as order_id,FROM_UNIXTIME(a.addtime) as order_time,
                    d.name as shangjia_name,c.id as f_id,c.worker_id,c.updated_at,c.status from ".tablename(t_record)." as a ".
                " left join ".tablename(sj_mulit_products)." as b on a.themeid = b.themeid ".
                " left join ".tablename(sj_mulit_products_user_flag)." as c on a.uid=c.uid and b.id=c.product_id ".
                " left join ".tablename(t_shangjia)." as d on d.id=b.shangjiaid ".
                " where a.themeid=$themeid  and b.status=1 ".$condition;
            return db_select($sql);
        }

    }

    /**
     * Desc:创建产品item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/18 10:38
     * @param $data
     * @return mixed
     */
    public static function insertProductItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return $insertid = db_insert(sj_mulit_products,$data);
    }

    /**
     * Desc:更新产品item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/18 10:38
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editProductItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(sj_mulit_products,$data,$where);
    }

    /**
     * Desc:获取员工手机号
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/8/9 10:47
     * @param $where
     * @return mixed
     */
    public static function getWorkerMobile($where)
    {
        return db_get(t_worker,$where);
    }

    /**
     * Desc:获取产品item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/18 13:05
     * @param $where
     * @return mixed
     */
    public static function getProductItem($where)
    {
        return db_get(sj_mulit_products,$where);
    }

    /**
     * Desc:获取查询条件下的商家列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/11/15 9:35 上午
     * @param $where
     * @return mixed
     */
    public  static function getShangjiaList()
    {
        $sql = " select * from ".tablename(t_shangjia)." where id >0 and state=1 order by displayorder";
        return db_select($sql);
    }

    /**
     * Desc:删除产品item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/18 10:38
     * @param $where
     * @return mixed
     */
    public static function delProductItem($where)
    {
        return db_delete(sj_mulit_products,$where);
    }

    /**
     * Desc:获取支付成功订单数【线上加线下】
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/8/9 15:43
     * @param $themeid
     * @return mixed
     */
    public static function getOrderTotalByWhere($themeid)
    {
        $sql = " select count(*) as cnt from ".tablename(t_record)." where themeid='$themeid' and (status=1 or status=3) ";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:更新产品用户记录item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/18 10:38
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editFlagItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        return db_update(sj_mulit_products_user_flag,$data,$where);
    }

    /**
     * Desc:获取商家下的产品数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/20 15:09
     * @param $themeid
     * @param $sj_id
     * @return mixed
     */
    public static function getSjProductTotal($themeid,$sj_id)
    {
        $sql = " select count(*) as cnt from ".tablename(sj_mulit_products)." where themeid='$themeid' and shangjiaid='$sj_id'";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取状态下的产品数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/21 14:09
     * @param $themeid
     * @param int $status
     * @return mixed
     */
    public static function getSjProductStatusTotal($themeid,$status=0,$sj_id =0)
    {
        $sql = " select count(*) as cnt from ".tablename(sj_mulit_products)." where themeid='$themeid' and status='$status' ";
        if ($sj_id){
            $sql .= " and shangjiaid='$sj_id'";
        }
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:通过商家名称或者
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/21 17:10
     * @param $themeid
     * @param string $name
     * @return mixed
     */
    public static function getSjIdByName($themeid,$name='')
    {
        $sql = " select * from ".tablename(t_shangjia)." where id >0 and name='$name' and state=1 order by displayorder";
        return db_find($sql);
    }

    /**
     * Desc:获取当前的产品的记录数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/22 10:04
     * @param $themeid
     * @param int $pid
     * @return mixed
     */
    public static function getUserProductFlagTotal($themeid,$pid=0,$sj_id =0,$status=0,$order_id=0)
    {
        $condition = "";
        if ($pid){
            $condition .= " and product_id='$pid' ";
        }
        if ($sj_id){
            $condition .= " and shangjiaid='$sj_id' ";
        }
        if ($status){
            $condition .= " and status='$status' ";
        }
        if ($order_id){
            $condition .= " and order_id='$order_id' ";
        }
        $sql = " select count(*) as cnt from ".tablename(sj_mulit_products_user_flag)." where themeid='$themeid' ".$condition;
        return db_find($sql)['cnt'];
    }


    public static function insertUserAllProductFlag($themeid,$uid,$order_id,$type='all',$pids = '',$worker_id=0,$sj_id=0)
    {
        if ($uid && $themeid && $order_id){
            $condition = "";
            if ($sj_id){
                $condition .=" and a.shangjiaid=$sj_id";
            }
            if ($type=='more'){
                $condition .= " and a.id in (".$pids.") ";
            }elseif ($type=='only'){
                $condition .= " and a.id=$pids ";
            }elseif ($type=='all'){
                //判断是all 判断是否存在核销记录
                $sql = " select product_id from ".tablename(sj_mulit_products_user_flag)." where themeid='$themeid' and order_id='$order_id' and shangjiaid='$sj_id' ";
                $list = db_select($sql);
                if ($list && count($list)>0){
                    //存在核销记录  获取未核销的pids
                    $diff_pids = "";
                    foreach ($list as $v){
                        $diff_pids .= $v['product_id'].',';
                    }
                    $new_diff_pids = rtrim($diff_pids,',');
                    //获取改商家下未核销的pids
                    $sql2 = " select id from ".tablename(sj_mulit_products)." where themeid='$themeid' and  shangjiaid='$sj_id' and  status=1 and id not in (".$new_diff_pids.") ";
                    $new_list = db_select($sql2);
                    if ($new_list){
                        $look_pids = "";
                        foreach ($new_list as $v1){
                            $look_pids .= $v1['id'].',';
                        }
                        $look_pids = rtrim($look_pids,',');
                        $condition .= " and a.id in (".$look_pids.") ";
                    }
                }
            }
            $sql = " SELECT a.* FROM ".tablename(sj_mulit_products)." as a".
                " LEFT JOIN ".tablename(t_shangjia)." AS b ON a.shangjiaid=b.id and b.state=1".
                " WHERE themeid=$themeid and a.status=1 ".$condition;
            $plist = db_select($sql);
            if ($plist){
                $data_values = '';
                foreach ($plist as $key => $val){
                    $shangjiaid = $val['shangjiaid'];
                    $product_id = $val['id'];
                    $status = 2;
                    $updated_at = date('Y-m-d H:i:s');
                    $data_values .= "('$order_id','$uid','$shangjiaid','$product_id','$worker_id','$status','$updated_at','$themeid'),";
                }
                $data_values = substr($data_values,0,-1); //去掉最后一个逗号
                $sql = "INSERT INTO ".tablename(sj_mulit_products_user_flag).
                    " (`order_id`, `uid`, `shangjiaid`,`product_id`,`worker_id`,`status`,`updated_at`,`themeid`) VALUES $data_values";//sql语句
                $res = db_query($sql);

            }
        }
    }

    /**
     * Desc:格式化订单中的用户的产品信息核销
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/23 11:09
     */
    public static function formatRecordUserProductsInfo($themeid,$uid,$order_id)
    {
        $sql = " select a.*,b.name,c.name as sj_name from ".tablename(sj_mulit_products_user_flag)." as a ".
        " LEFT JOIN ".tablename(sj_mulit_products)." AS b ON a.product_id=b.id ".
        " LEFT JOIN ".tablename(t_shangjia)." AS c ON a.shangjiaid=c.id ".
            " where a.themeid='$themeid' and a.uid='$uid' and a.order_id='$order_id' order by a.status desc";
        return db_select($sql);
    }

    /**
     * Desc:获取用户多产品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/22 11:57
     * @param $themeid
     * @param $uid
     * @param $order_id
     * @return mixed
     */
    public static function getUserAllProductFlag($themeid,$uid,$order_id)
    {
        $condition = " and b.status=1";
        if ($order_id){
            $condition .= " and a.id='".$order_id."'";
        }
        $condition .= " and (a.status=1 or a.status=3)  ";

        $sql = " select a.nickname,a.username,a.mobile,a.avatar,b.shangjiaid,b.name,a.id as order_id,FROM_UNIXTIME(a.addtime) as order_time,
                    d.name as shangjia_name,b.id as product_id,c.worker_id,c.updated_at,c.status,c.id as f_id from ".tablename(t_record)." as a ".
            " left join ".tablename(sj_mulit_products)." as b on a.themeid = b.themeid ".
            " left join ".tablename(sj_mulit_products_user_flag)." as c on a.uid=c.uid and b.id=c.product_id ".
            " left join ".tablename(t_shangjia)." as d on d.id=b.shangjiaid ".
            " where a.themeid=$themeid  and a.uid=$uid".$condition;
        return db_select($sql);


//        $sql = " select a.*,b.name from ".tablename(sj_mulit_products_user_flag)." as a".
//            " LEFT JOIN ".tablename(sj_mulit_products)." AS b ON a.product_id=b.id ".
//            " where a.themeid='$themeid' and a.uid=$uid and a.order_id='$order_id' order by a.status desc";
//        return db_select($sql);
    }

    /**
     * Desc:通过条件获取用户的记录数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/23 10:21
     * @param $themeid
     * @param int $uid
     * @param int $order_id
     * @param int $sj_id
     * @param int $status
     * @return mixed
     */
    public static function getUserProductTotalBySjId($themeid,$uid=0,$order_id=0,$sj_id=0,$status=-1,$p_id=0)
    {
        $condition = '';
        if ($uid){
            $condition.= " and uid='$uid' ";
        }
        if ($order_id){
            $condition.= " and order_id='$order_id' ";
        }
        if ($sj_id){
            $condition.= " and shangjiaid='$sj_id' ";
        }
        if ($status>-1){
            $condition.= " and status='$status' ";
        }
        if ($p_id){
            $condition.= " and product_id='$p_id' ";
        }
        $sql = " select count(*) as cnt from ".tablename(sj_mulit_products_user_flag)." where themeid='$themeid'".$condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取用户指定商家的多产品核销记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/23 13:24
     * @param $themeid
     * @param int $uid
     * @param int $order_id
     * @param int $sj_id
     * @return mixed
     */
    public static function getUserSjProductBySjId($themeid,$uid=0,$order_id=0,$sj_id=0)
    {
        $sql = " select a.*,b.name from ".tablename(sj_mulit_products_user_flag)." as a".
            " LEFT JOIN ".tablename(sj_mulit_products)." AS b ON a.product_id=b.id ".
            " where a.themeid='$themeid' and a.uid=$uid and a.order_id='$order_id' and a.shangjiaid='$sj_id' ";
        return db_select($sql);
    }

    public static function formatAdminMulitInfo($baseinfo)
    {
        global $_P, $_G;
        $worker = $baseinfo['myworker'];
        $theme = $baseinfo['theme'];
        $system = $baseinfo['system'];
        $op = isset($_P['op'])?$_P['op']:'';
        $uid = isset($_P['uid'])?$_P['uid']:'';
        $sj_id = isset($_P['sj_id'])?$_P['sj_id']:'';
        $p_id = isset($_P['p_id'])?$_P['p_id']:'';
        $page = $_P['page']?$_P['page']:1;
        $hasNext = true;
        $page_index = max(1,intval($page));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $themeid = intval($_P['themeid']);
        $shangjia_list = [];
        if ($worker['level']==1){
            $shangjia_list = self::getShangjiaList();
            $shangjia_arr = [];
            $shangjia_total = 0;
            foreach ($shangjia_list as $k => $v){
                $item_total = (int)self::getSjProductTotal($themeid,$v['id']);
                $order_total = (int)self::getOrderTotalByWhere($themeid);
                $tmp_total = ($item_total * $order_total);
                $tmp_arr = [
                    'sj_id'=>$v['id'],
                    'title'=>$v['name'],
                    'total'=>$tmp_total
                ];
                $shangjia_total +=$tmp_total;
                array_push($shangjia_arr,$tmp_arr);
            }
            array_unshift($shangjia_arr,['sj_id'=>0,'title'=>'全部商家','total'=>$shangjia_total]);
        }else{
            if (!$sj_id){
                $sj_id = $worker['company'];
            }
            $product_arr = self::getSjProductList($themeid,'',1,$sj_id,0,0);
            $prize_arr = [];
            $prize_total = 0;
            foreach ($product_arr as $k => $v){
                $tmp_total = (int)self::getOrderTotalByWhere($themeid);
                $tmp_arr = [
                    'p_id'=>$v['id'],
                    'title'=>$v['name'],
                    'total'=>$tmp_total
                ];
                $prize_total += $tmp_total;
                array_push($prize_arr,$tmp_arr);
            }
            array_unshift($prize_arr,['p_id'=>0,'title'=>'全部','total'=>$prize_total]);
        }
        $total = self::getUserRecordSjProductList($themeid,'',$sj_id,$p_id,0,0,true,0,0);
        $list = self::getUserRecordSjProductList($themeid,'',$sj_id,$p_id,$page_start,$page_size,false,0,0);
        $worklist = Worker::getworkerlist($system,$themeid);
        foreach ($list as $key => $row){
            if ($row['f_id']){
                if(!empty($row['worker_id'])){
                    $r = Worker::getWokerName($system,$themeid,$row['worker_id'],$worklist);
                    $list[$key]['workername']=$r['workername'];
                    $list[$key]['teamname']=$r['teamname'];
                    $list[$key]['companyname']=$r['companyname'];
                }
            }else{
                $list[$key]['status'] = 1;
            }
        }
//        $statusArr = array_column($list, 'status');
//        array_multisort($statusArr,SORT_ASC,$list);

        $max_page = (int)ceil($total/$page_size);
        if ($max_page<=$page){
            $hasNext = false;
        }
        $dd =[
            'uid'=>$uid,
            'worker'=>$worker,
            'shangjia_arr'=>$shangjia_arr,
            'prize_arr'=>$prize_arr,
            'sj_id'=>$sj_id,
            'p_id'=>$p_id,
            'list'=>$list,
            'page'=>$page,
            'hasNext'=>$hasNext,
            'page_size'=>$page_size,
            'max_page'=>$max_page,
        ];
        return $dd;
    }
}